package com.doudoukeji.service.Utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.util.Base64;

import com.doudoukeji.service.Activity.ConstantValue;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * 处理图片工具类
 *
 * @author nseer
 */
public class PictureUtil {

    private static BitmapFactory.Options newOpts;

    /**
     * 把bitmap转换成String
     *
     * @param filePath
     * @return
     */
    public static String bitmapToString(String filePath) {

        Bitmap bm = getSmallBitmap(filePath);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 40, baos);
        byte[] b = baos.toByteArray();

        return Base64.encodeToString(b, Base64.DEFAULT);

    }

    /**
     * 计算图片的缩放值
     *
     * @param options
     * @param reqWidth
     * @param reqHeight
     * @return
     */
    public static int calculateInSampleSize(BitmapFactory.Options options,
                                            int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height
                    / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }

    /**
     * 根据路径获得突破并压缩返回bitmap用于显示
     *
     * @param filePath
     * @return
     */
    @SuppressWarnings("static-access")
    public static Bitmap getSmallBitmap(String filePath) {


        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        options.inSampleSize = calculateInSampleSize(options, 480, 800);
        options.inJustDecodeBounds = false;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        options.inPurgeable = true;
        LogUtil.info("inSampleSize====" + options.inSampleSize, ConstantValue.currentStage);
        Bitmap resizedBitmap;
        try {
            resizedBitmap = BitmapFactory.decodeFile(filePath, options);
        } catch (OutOfMemoryError e) {

            resizedBitmap = null;
            System.gc();
            return null;
        }
        return resizedBitmap;
    }

    /**
     * 根据路径删除图片
     *
     * @param path
     */
    public static void deleteTempFile(String path) {
        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }
    }

    /**
     * 根据路径获取压缩过的bitmap
     *
     * @param srcPath
     * @return
     */
    public static Bitmap getimage(String srcPath) {
//	int degree = 	readPictureDegree(srcPath);
//	LogUtil.info("degree===="+degree);
        newOpts = new BitmapFactory.Options();
        newOpts.inPreferredConfig = Bitmap.Config.RGB_565;
        //开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);//此时返回bm为空
//		newOpts.inPreferredConfig = Config.RGB_565;  
        newOpts.inJustDecodeBounds = false;

        int width = newOpts.outWidth;
        int height = newOpts.outHeight;
        LogUtil.info("width======" + width, ConstantValue.currentStage);
        LogUtil.info("height======" + height, ConstantValue.currentStage);
        //现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
        float reqHeight = 800f;//这里设置高度为800f
        float reqWidth = 480f;//这里设置宽度为480f
        //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;//be=1表示不缩放
        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height
                    / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            be = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;//设置缩放比例
        //重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        try {
            bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        } catch (OutOfMemoryError e) {
            if (bitmap != null && !bitmap.isRecycled()) {
                bitmap.recycle();
            }
            System.gc();
            return null;
        }

        return compressImage(bitmap);
//		if(bitmap==null){
//			return null ;
//		}
//		int newwidth=bitmap.getWidth();
//		int newheight = bitmap.getHeight();
//		if(height>width){
//			Matrix matrix = new Matrix();
//		     // resize the bit map
//		     matrix.postRotate(90);
//		     Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, newwidth, newheight, matrix, true);
//		     return resizedBitmap;
//		}else{
//			Matrix matrix = new Matrix();
//		     // resize the bit map
//		     matrix.postRotate(0);
//		     Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, newwidth, newheight, matrix, true);
//		     return resizedBitmap;
//		}
//		bitmap=ResizeBitmap(srcPath,bitmap);
    }


    public static Bitmap compressImage(Bitmap image) {
        if (image == null) {
            return null;
        }
        Bitmap resizedBitmap;
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
            int options = 100;
            while (options > 70 && (baos.toByteArray().length / 1024) > 210) {    //循环判断如果压缩后图片是否大于100kb,大于继续压缩
                baos.reset();//重置baos即清空baos
                image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
                options -= 10;//每次都减少10
            }
            ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
            newOpts.inPurgeable = true;


            resizedBitmap = BitmapFactory.decodeStream(isBm, null, newOpts);//把ByteArrayInputStream数据生成图片
        } catch (OutOfMemoryError e) {

            resizedBitmap = null;
            image.recycle();
            System.gc();
            return null;
        }
        return resizedBitmap;
    }

    /**
     * 添加到图库
     */
    public static void galleryAddPic(Context context, String path) {
        Intent mediaScanIntent = new Intent(
                Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File f = new File(path);
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);
        context.sendBroadcast(mediaScanIntent);
    }

    /**
     * 获取保存图片的目录
     *
     * @return
     */
    public static File getAlbumDir() {
        File dir = new File(
                Environment.getExternalStorageDirectory(),
                getAlbumName());
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return dir;
    }

    /**
     * 获取保存 隐患检查的图片文件夹名称
     *
     * @return
     */
    public static String getAlbumName() {
        return "ahb";
    }

    public static Bitmap getLocalBitmap(Uri photoUri) {
        String path = photoUri.toString();
        Bitmap bitmap = null;
        InputStream in = null;
        BufferedOutputStream out = null;
        try {
            in = new BufferedInputStream(new URL(path).openStream(), 2 * 1024);
            final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
            out = new BufferedOutputStream(dataStream, 2 * 1024);
            copy(in, out);
            out.flush();
            byte[] data = dataStream.toByteArray();
            final BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeByteArray(data, 0, data.length, options);
            options.inSampleSize = calculateInSampleSize(options, 480, 800);
            options.inJustDecodeBounds = false;
            LogUtil.info("inSampleSize====" + options.inSampleSize, ConstantValue.currentStage);
            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
            data = null;
            return bitmap;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private static void copy(InputStream in, BufferedOutputStream out) throws IOException {
        byte[] b = new byte[2 * 1024];
        int read;
        while ((read = in.read(b)) != -1) {
            out.write(b, 0, read);
        }
    }

    /**
     * 把程序拍摄的照片放到 SD卡的 Pictures目录中 sheguantong 文件夹中
     * 照片的命名规则为：sheqing_20130125_173729.jpg
     *
     * @return
     * @throws IOException
     */
    @SuppressLint("SimpleDateFormat")
    public static File createImageFile() throws IOException {

        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_HHmmss");
        String timeStamp = format.format(new Date());
        String imageFileName = "ahb_" + timeStamp + ".jpg";

        File image = new File(PictureUtil.getAlbumDir(), imageFileName);
        return image;
    }

}
